<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="单据编号" prop="checkOutNo">
        <el-input
          v-model="queryParams.checkOutNo"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>
      <el-form-item label="老人姓名" prop="elderlyName">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>

<el-form-item label="老人身份证号"  prop="elderlyIdCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>

<br/>

      <el-form-item label="退住日期" style="width: 380px">
        <el-date-picker
          v-model="daterangeCheckOutDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


<hr/>

<!-- 权限控制：只有护理员a才能点击发起退住申请按钮 -->
<button 
  v-if="canCreateCheckoutApplication"
  class="apply1" 
  style="float: right;" 
  type="primary" 
  @click="handleApply"
>发起退住申请</button>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:out_management:add']"
        >新增</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:out_management:edit']"
        >修改</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:out_management:remove']"
        >删除</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:out_management:export']"
        >导出</el-button> -->
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="out_managementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template #default="scope">
          {{ total - (queryParams.pageNum - 1) * queryParams.pageSize - scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="单据编号" align="center" prop="checkOutNo" />


   <el-table-column label="老人姓名" align="center" prop="elderly.name" />
      <el-table-column label="老人身份证号" align="center" prop="elderly.idCard" />


      <el-table-column label="退住日期" align="center" prop="checkOutDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkOutDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

  
 
      <el-table-column label="创建人" align="center" prop="sysUser.nickName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:out_management:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:out_management:remove']">删除</el-button> -->
             <el-button link type="primary"  @click="review(scope.row)" >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改退住办理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="out_managementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人外键编号" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键编号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Out_management">
import { listOut_management, getOut_management, delOut_management, addOut_management, updateOut_management } from "@/api/system/out_management"
import { listTasks } from "@/api/system/tasks"
import { routerViewLocationKey } from "vue-router"
import { useRouter } from 'vue-router'
import { parseTime } from '@/utils/ruoyi'
import useUserStore from '@/store/modules/user'

const router = useRouter()
const userStore = useUserStore()

const { proxy } = getCurrentInstance()

// ✅ 权限控制：检查当前用户是否有权限发起退住申请
const canCreateCheckoutApplication = computed(() => {
  const currentUser = userStore.name
  console.log('当前用户:', currentUser)
  
  // 只有护理员a (huliyuana) 才能发起退住申请
  if (currentUser === 'huliyuana') {
    console.log('✅ 护理员a，允许发起退住申请')
    return true
  }
  
  console.log('❌ 非护理员a，不能发起退住申请')
  return false
})

const out_managementList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeCheckOutDate = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    checkOutNo: null,
    elderlyId: null,
    checkOutDate: null,
    isDeleted: null,
    businessId: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询退住办理列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCheckOutDate && '' != daterangeCheckOutDate) {
    queryParams.value.params["beginCheckOutDate"] = daterangeCheckOutDate.value[0]
    queryParams.value.params["endCheckOutDate"] = daterangeCheckOutDate.value[1]
  }
  listOut_management(queryParams.value).then(response => {
    // 将数据倒序排列
    out_managementList.value = response.rows.reverse()
    total.value = response.total
    loading.value = false
    console.log('倒序后的数据:', out_managementList.value)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    checkOutNo: null,
    elderlyId: null,
    checkInManagementId: null,
    bedId: null,
    checkOutDate: null,
    checkOutReason: null,
    remark: null,
    creator: null,
    createTime: null,
    updateTime: null,
    isDeleted: null,
    businessId: null,
    elderlyName: null,
    elderlyIdCard: null,
    nick_name: null,
    extraField1: null,
    extraField2: null,

  }
  proxy.resetForm("out_managementRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCheckOutDate.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加退住办理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOut_management(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改退住办理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["out_managementRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOut_management(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOut_management(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除退住办理编号为"' + _ids + '"的数据项？').then(function() {
    return delOut_management(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/out_management/export', {
    ...queryParams.value
  }, `out_management_${new Date().getTime()}.xlsx`)
}

// 发起退住申请
function handleApply() {
  router.push('/system/out_management/checkoutForm')
}

// 查看详情（根据待办任务状态选择性跳转到不同页面）
async function review(row) {
  console.log('=== 查看退住详情 ===')
  console.log('退住数据:', row)
  console.log('业务ID:', row.id)
  
  try {
    // 1. 根据业务ID查询待办任务
    const response = await listTasks({
      bussniessId: row.id, // 使用退住记录的ID作为业务ID
      type: 1 // 退住申请类型
    })
    
    console.log('待办任务查询结果:', response)
    
    if (response.code === 200 && response.rows && response.rows.length > 0) {
      console.log('所有待办任务详情:')
      response.rows.forEach((task, index) => {
        console.log(`任务${index + 1}:`, {
          id: task.id,
          stepNo: task.stepNo,
          title: task.title,
          isHandle: task.isHandle,
          status: task.status,
          createTime: task.createTime,
          finishTime: task.finishTime
        })
      })
      
      // 1. 首先检查是否有被拒绝的任务
      const rejectedTask = response.rows.find(task => {
        const isRejected = task.isHandle === 1 && task.status === 3
        console.log(`任务${task.stepNo}拒绝状态检查:`, {
          isRejected: isRejected,
          isHandle: task.isHandle,
          status: task.status,
          statusDesc: task.isHandle === 1 ? 
            (task.status === 1 ? '申请中' : 
             task.status === 2 ? '已通过' : 
             task.status === 3 ? '已拒绝' : '未知状态') : '未处理'
        })
        return isRejected
      })
      
      if (rejectedTask) {
        console.log('存在被拒绝的任务，跳转到审批被拒绝页面')
        router.push({
          path: '/tuizhuceshi/spbjj',
          query: {
            step: rejectedTask.stepNo,
            id: row.id
          }
        })
        return
      }
      
      // 2. 检查第7步的待办任务状态
      const step7Task = response.rows.find(task => task.stepNo === 7)
      
      if (step7Task && step7Task.isHandle === 1) {
        // 第7步已完成 → 跳转到审批通过页面
        console.log('第7步已完成，跳转到退住申请审批通过页面')
        router.push({
          path: '/tuizhuceshi/tuizhushenpitongguo',
          query: {
            id: row.id
          }
        })
        return
      }
      
      // 3. 检查是否有正在审批中的任务（第2步）
      const step2Task = response.rows.find(task => task.stepNo === 2)
      
      if (step2Task && step2Task.isHandle === 0) {
        // 第2步未完成 → 跳转到审批中页面
        console.log('第2步未完成，跳转到申请审批页面（审批中状态）')
        router.push({
          path: '/tuizhuceshi/shenqingshenpi',
          query: {
            id: row.id,
            mode: 'approval',
            step: 2
          }
        })
        return
      }
      
      // 4. 默认情况：跳转到审批中页面
      console.log('默认情况，跳转到申请审批页面（审批中状态）')
      router.push({
        path: '/tuizhuceshi/shenqingshenpi',
        query: {
          id: row.id,
          mode: 'approval',
          step: 2
        }
      })
      
    } else {
      // 如果没有找到待办任务，跳转到审批中页面
      console.log('未找到待办任务，跳转到申请审批页面（审批中状态）')
      router.push({
        path: '/tuizhuceshi/shenqingshenpi',
        query: {
          id: row.id,
          mode: 'approval',
          step: 2
        }
      })
    }
  } catch (error) {
    console.error('查询待办任务失败:', error)
    proxy.$modal.msgError('查询待办任务失败：' + (error.message || '未知错误'))
  }
}

getList()
</script>


<style scoped>
.apply1{
  /* margin-left: 1500px; */
  width: 130px;
  height: 28px;
  background-color: #0000FF;
  color: white;
  border-style: none;
border-radius: 5px;
}
</style>